// 哈希表 数组+链表 或 数组+二叉树
class HashTable {
    hashList = []

    constructor (size) {
        this.size = size
        for (let i = 0; i < size; i++) {
            this.hashList.push(new EmpLinkedList())
        }
    }

    /**
     *
     * @param emp{Emp}
     */
    add (emp) {
        let no = this.hashFun(~~emp.id)
        this.hashList[no].add(emp)
    }

    list () {
        for (let i = 0; i < this.size; i++) {
            console.log('=====', i)
            this.hashList[i].list()
        }
    }

    find (id) {
        let no = this.hashFun(id)
        let temp = this.hashList[no].find(id)
        if (temp !== null) {
            console.log(temp.id, temp.name)
        } else {
            console.log('没有找到')
        }
    }

    /**
     * 编写散列函数
     * @param id{number}
     */
    hashFun (id) {
        return id % this.size
    }
}

class EmpLinkedList {
    head = null

    /**
     *
     * @param emp{Emp}
     */
    add (emp) {
        if (this.head === null) {
            this.head = emp
            return
        }
        let empTemp = this.head
        while (true) {
            if (empTemp.next === null) {
                break
            }
            empTemp = empTemp.next
        }
        empTemp.next = emp

    }

    list () {
        if (this.head === null) {
            console.log('链表为空')
            return
        }
        let empTemp = this.head
        while (true) {
            console.log(`=> id=${empTemp.id} name=${empTemp.name}`)
            if (empTemp.next === null) {
                break
            }
            empTemp = empTemp.next
        }
    }

    find (id) {
        if (this.head === null) {
            console.log('链表为空')
            return null
        }
        let temp = this.head
        while (true) {
            if (temp.id === id) {
                break
            }
            if (temp.next === null) {
                temp = null
                break
            }
            temp = temp.next
        }
        return temp
    }
}

class Emp {
    id = ''
    name = ''
    next = null

    constructor (id, name) {
        this.id = id
        this.name = name
    }
}

function main () {
    let hashTab = new HashTable(7)
    for (let i = 0; i < 100; i++) {
        hashTab.add(new Emp(i, `雇员${i}`))
    }
    hashTab.list()
    hashTab.find(7)
    hashTab.find(98)
}

main()
